package com.lining.orangeservice.entity.abstractentity.impl;

import com.lining.orangeservice.common.enums.OrderStatus;
import com.lining.orangeservice.entity.abstractentity.Order;
import com.lining.orangeservice.entity.po.OrderItem;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 团购订单
 */
public class GroupBuyOrder extends Order {
    private Long groupActivityId;
    private Integer requiredMembers;  // 需要成团人数
    private Integer currentMembers;   // 当前参团人数
    private LocalDateTime groupExpireTime;
    
    @Override
    public void calculateAmount() {
        if (items == null || items.isEmpty()) {
            totalAmount = BigDecimal.ZERO;
            discountAmount = BigDecimal.ZERO;
            actualAmount = BigDecimal.ZERO;
            return;
        }
        
        totalAmount = items.stream()
            .map(OrderItem::getSubTotal)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 团购订单：固定折扣
        BigDecimal groupDiscountRate = new BigDecimal("0.7"); // 7折
        discountAmount = totalAmount.multiply(BigDecimal.ONE.subtract(groupDiscountRate));
        actualAmount = totalAmount.subtract(discountAmount);
    }
    
    @Override
    public boolean canCancel() {
        // 团购订单在成团前可以取消
        return status == OrderStatus.PENDING && 
               LocalDateTime.now().isBefore(groupExpireTime);
    }
    
    @Override
    public boolean canRefund() {
        // 团购订单成团后不能退款
        return status == OrderStatus.PAID && currentMembers < requiredMembers;
    }
    
    public boolean joinGroup(Long userId) {
        if (currentMembers >= requiredMembers) {
            return false; // 团已满
        }
        if (LocalDateTime.now().isAfter(groupExpireTime)) {
            return false; // 团购已过期
        }
        currentMembers++;
        
        // 如果达到成团人数，更新订单状态
        if (currentMembers >= requiredMembers) {
            updateStatus(OrderStatus.PAID);
        }
        return true;
    }

    // getters and setters
    public Long getGroupActivityId() {
        return groupActivityId;
    }

    public void setGroupActivityId(Long groupActivityId) {
        this.groupActivityId = groupActivityId;
    }

    public Integer getRequiredMembers() {
        return requiredMembers;
    }

    public void setRequiredMembers(Integer requiredMembers) {
        this.requiredMembers = requiredMembers;
    }

    public Integer getCurrentMembers() {
        return currentMembers;
    }

    public void setCurrentMembers(Integer currentMembers) {
        this.currentMembers = currentMembers;
    }

    public LocalDateTime getGroupExpireTime() {
        return groupExpireTime;
    }

    public void setGroupExpireTime(LocalDateTime groupExpireTime) {
        this.groupExpireTime = groupExpireTime;
    }
}